/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.mvc.render;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import com.jianggujin.modulelink.mvc.JActionContext;
import com.jianggujin.modulelink.mvc.render.JErrorRender.JErrorRenderParam;
import com.jianggujin.modulelink.mvc.util.JWebUtils;
import com.jianggujin.modulelink.util.JAssert;
import com.jianggujin.modulelink.util.JStringUtils;

/**
 * 异常渲染
 * 
 * @author jianggujin
 *
 */
public class JErrorRender implements JRender<JErrorRenderParam> {
   public static final JErrorRenderParam ERROR_500 = new JErrorRenderParam(500);
   public static final JErrorRenderParam ERROR_404 = new JErrorRenderParam(404);

   @Override
   public void render(JActionContext context, JErrorRenderParam param) throws IOException, ServletException {
      JAssert.checkNotNull(context, "context must not be null");
      JAssert.checkNotNull(param, "param must not be null");
      HttpServletResponse response = context.getResponse();
      String encoding = JWebUtils.getResponseEncoding(context.getResponse());
      response.setContentType("text/xml; charset=" + encoding);
      if (JStringUtils.isBlank(param.getMsg())) {
         response.sendError(param.getCode());
      } else {
         response.sendError(param.getCode(), param.getMsg());
      }
   }

   public static class JErrorRenderParam {
      private int code = 500;
      private String msg;

      public JErrorRenderParam(int code) {
         this.code = code;
      }

      public JErrorRenderParam(int code, String msg) {
         this.code = code;
         this.msg = msg;
      }

      public int getCode() {
         return code;
      }

      public void setCode(int code) {
         this.code = code;
      }

      public String getMsg() {
         return msg;
      }

      public void setMsg(String msg) {
         this.msg = msg;
      }
   }

}
